package com.vader.juc.lock;

import javax.xml.transform.Source;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author kaivader
 */
class Sources {
    public int number = 1;

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void one() throws InterruptedException {
        lock.lock();
        try {
            while (number != 1) {
                condition.await();
            }
            number=2;
            System.out.println(Thread.currentThread().getName() + "：：" + number);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void two() throws InterruptedException {
        lock.lock();
        try {
            while (number != 2) {
                condition.await();
            }
            number=3;
            System.out.println(Thread.currentThread().getName() + "：：" + number);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void three() throws InterruptedException {
        lock.lock();
        try {
            while (number != 3) {
                condition.await();
            }
            number=1;
            System.out.println(Thread.currentThread().getName() + "：：" + number);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}

/**
 * @author kaivader
 */
public class FeaturnLockDemo {
    public static void main(String[] args) {
        Sources sources = new Sources();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    sources.one();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    sources.two();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 15; i++) {
                try {
                    sources.three();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();

    }
}
